﻿Option Explicit On
Option Strict On

Imports DARSClassLibrary
Imports DBUtilitiesLibrary
Imports System.Data.SqlClient
Imports System.Net.Mail
Public Class PasswordRecovery
    Inherits System.Web.UI.Page
    Dim ws As New DO_NOT_MOVE_ME_FROM_THIS_PROJECT.DARSWebservice
    Dim objdb As New DARSDBConnection
    Dim type As String
    Dim ds As New DataSet
    Dim reader As SqlDataReader
    Dim username As String
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            btnSubmit2.Visible = False
            txtAnswer1.Visible = False
            txtAnswer2.Visible = False
        End If
    End Sub

    Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSubmit.Click
        username = txtUserID.Text.Trim
        If Not ValidateUser(username) = "" Then
            lblErr.Text = ValidateUser(username)
            Exit Sub
        Else
            'Checks if radio button is checked
            If RadioChk() <> "" Then
                lblErr.Text = RadioChk()
                Exit Sub
            Else
                If rdbtype.SelectedIndex = 0 Then
                    type = rdbtype.SelectedValue
                ElseIf rdbtype.SelectedIndex = 1 Then
                    type = rdbtype.SelectedValue
                End If
            End If
            'Makes sure that user exists in user's account type table
            If ValidateUserType(username, type) <> "" Then
                lblErr.Text = ValidateUserType(username, type)
                Exit Sub
            End If
        End If
        Try
            Dim sql As String = "SELECT * FROM UserTable WHERE UserID = '" & username & "'"
            ds = objdb.getDataSet(sql)
            If ds.Tables(0).Rows.Count = 0 Then
                lblErr.Text = "The username entered does not exist"
                Exit Sub
            End If
            btnSubmit2.Visible = True
            txtAnswer1.Visible = True
            txtAnswer2.Visible = True
            lblErr.Text = ""
            btnSubmit.Visible = False
            rdbtype.Visible = False
            getUserQuestion(username)
        Catch ex As Exception
            lblErr.Text = "An error occured. Try again"
        End Try
    End Sub
    'Checks to se if User is in the table of given type
    Protected Function ValidateUserType(ByRef username As String, ByRef type As String) As String
        Dim dsfindtype As DataSet
        If type = "Advisor" Then
            Dim sql As String = "Select UserID FROM Advisor WHERE UserID = '" & username & "'"
            dsfindtype = objdb.getDataSet(sql)
            If dsfindtype.Tables(0).Rows.Count = 0 Then
                Return "Username was not found. Please make sure the information correct."
            Else
                Return ""
            End If
        Else
            Dim sql2 As String = "Select UserID FROM Student WHERE UserID = '" & username & "'"
            dsfindtype = objdb.getDataSet(sql2)
            If dsfindtype.Tables(0).Rows.Count = 0 Then
                Return "Username was not found. Please make sure the information is correct"
            Else
                Return ""
            End If
        End If
    End Function
    'Checks to see if user input is correct
    Protected Function ValidateUser(ByVal txt As String) As String
        If txt = "" Then
            Return "Username cannot be empty"
        Else
            Return ""
        End If
    End Function
    'Checks to see if any radio button options were selected
    Protected Function RadioChk() As String
        If rdbtype.SelectedIndex = 0 Then
            Return ""
        ElseIf rdbtype.SelectedIndex = 1 Then
            Return ""
        Else
            Return "Please select if you are a student or an advisor."
        End If
    End Function
    'gets student's password and email from database
    Protected Sub getStudentInfo(ByRef user As String)
            Dim sql As String = "SELECT Password FROM UserTable WHERE UserID = '" & user & "'"
            Dim sql2 As String = "SELECT Email FROM Student WHERE UserID = '" & user & "'"
            reader = objdb.getDataReader(sql)
            reader.Read()
            Dim password = reader.Item("Password".ToString.Trim)
            reader.Close()
            reader = objdb.getDataReader(sql2)
            reader.Read()
            Dim email = reader.Item("Email".ToString.Trim)
            reader.Close()
            sendPassword(CStr(password), CStr(email))
    End Sub
    'gets Advisor's password and email from database
    Protected Sub getAdvisorInfo(ByRef user As String)
        Dim sql As String = "SELECT Password FROM UserTable WHERE UserID = '" & user & "'"
        Dim sql2 As String = "SELECT Email FROM Advisor WHERE UserID = '" & user & "'"
        reader = objdb.getDataReader(sql)
        reader.Read()
        Dim password = reader.Item("Password".ToString.Trim)
        reader.Close()
        reader = objdb.getDataReader(sql2)
        reader.Read()
        Dim email = reader.Item("Email".ToString.Trim)
        reader.Close()
        sendPassword(CStr(password), CStr(email))
    End Sub
    'Sends to email address
    Protected Sub sendPassword(ByRef password As String, ByRef email As String)
        Try
            Dim emailMessage As MailMessage = New MailMessage
            emailMessage.To.Add(New MailAddress(email))
            emailMessage.Priority = MailPriority.High
            emailMessage.Subject = "Beyond DARS Password Recovery"
            emailMessage.Body = "Thank you for using Beyond DARS. Your Password is: " & password

            Dim objSMTP As SmtpClient = New SmtpClient()
            objSMTP.Send(emailMessage)

            
            lblPasswordSent.Text = "Your password has been sent to " & email & ""
            pnlInput.Visible = False

            'Catch ex As SqlException
            ' Response.Write("<script>alert('Error: " & ex.Message & ".')</script>")
            ' Catch ex As SystemException
            'Response.Write("<script>alert('Error: " & ex.Message & ".')</script>")
        
            'End Try
        Catch ex As Exception
            lblErr.Text = "An error occured. Please try again"
        End Try
    End Sub
    'Gets user question and displays it in lablel lblSecret
    Protected Sub getUserQuestion(ByRef user As String)
        Dim sql As String = "SELECT SecurityQ1, SecurityQ2 FROM UserTable WHERE UserID = '" & user & "'"
        reader = objdb.getDataReader(sql)
        reader.Read()
        Dim SecurityQ = reader.Item("SecurityQ1".ToString)
        Dim SecurityQ2 = reader.Item("SecurityQ2".ToString)
        reader.Close()
        lblSecret1.Text = CStr(SecurityQ)
        lblsecret2.text = CStr(SecurityQ2)
        ' Session.Add("reader", reader)
    End Sub
    'Compares answers 
    Protected Function ChkSecurityAnswer(ByRef user As String) As Boolean
        user = txtUserID.Text
        Dim answer As String = CStr(txtAnswer1.Text.Trim)
        Dim answer2 As String = CStr(txtAnswer2.Text.Trim)
        Dim result As Boolean = False
        Dim sql As String = "SELECT SecurityA1, SecurityA2 FROM UserTable WHERE UserID = '" & user & "'"
        reader = objdb.getDataReader(sql)
        reader.Read()
        Dim SecurityA = reader.Item("SecurityA1").ToString.Trim
        Dim SecurityA2 = reader.Item("SecurityA2").ToString.Trim
        reader.Close()
        If answer = SecurityA And answer2 = SecurityA2 Then
            Return True
        Else
            Return False
        End If
    End Function
    'Calls a method that checks answer. If true, it will get type and call a method that will get and send the password to user.  
    Protected Sub btnSubmit2_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSubmit2.Click
        type = rdbtype.SelectedItem.Value
        If Not ChkSecurityAnswer(username) Then
            lblErr.Text = "You have entered an incorrect answer. Please try again"
            Exit Sub
        Else
            If type = "Student" Then
                getStudentInfo(username)
            ElseIf type = "Advisor" Then
                getAdvisorInfo(username)
            End If
        End If
    End Sub

    Protected Sub Welcome(ByVal sender As Object, ByVal e As EventArgs) Handles btnWelcome.ServerClick
        Response.Redirect("Welcome.aspx")
    End Sub

    

End Class